package com.leeson.portal.core.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.leeson.portal.core.model.Config;
import com.leeson.portal.core.model.OnlineMap;
import com.leeson.portal.core.service.InterfaceControl;
import com.leeson.portal.core.utils.SpringContextHelper;
import com.leeson.portal.manage.domain.Account;
import com.leeson.portal.manage.domain.LinkRecord;
import com.leeson.portal.manage.domain.LogRecord;
import com.leeson.portal.manage.service.AccountService;
import com.leeson.portal.manage.service.LinkRecordService;
import com.leeson.portal.manage.service.LogRecordService;

/**
 * 登录判断
 * 
 * @author LeeSon QQ:25901875
 */
public class Login extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1966047929923869408L;

	public Config config = Config.getInstance();

	Logger logger = Logger.getLogger(Login.class);
	OnlineMap onlineMap=OnlineMap.getInstance();
	
	String userState;
	Long userId;
	Date userDate;
	Long userTime;
	Long recordId;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		try {
			HttpSession session = request.getSession();
//			String username = (String) session.getAttribute("username");
//			String password = (String) session.getAttribute("password");
//			String ip = (String) session.getAttribute("ip");
			String ip = request.getRemoteAddr();
			boolean state=onlineMap.getOnlineUserMap().containsKey(ip);
			if(!state){
				session.removeAttribute("username");
				session.removeAttribute("password");
				session.removeAttribute("ip");
				request.setAttribute("msg", "你已经离线！");
				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
						response);
				return;
			}else {
				String[] loginInfo=onlineMap.getOnlineUserMap().get(ip);
				session.setAttribute("username", loginInfo[0]);
				session.setAttribute("ip", ip);
				session.setAttribute("password", loginInfo[0]);
				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/loginSucc.jsp").forward(request,
						response);
				return;
			}
			
			
			
//			if ((ip.equals("") || ip == null ||state==false)
//					|| (username.equals("") || username == null)
//					|| (password.equals("") || password == null)) {
//				request.setAttribute("msg", "请重新登录！");
//				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
//						response);
//				return;
//			} else {
//				request.setAttribute("msg", "请不要重复刷新！");
//				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
//						response);
//				return;
//			}

		} catch (Exception e) {
			// TODO: handle exception
			request.setAttribute("msg", "请重新登录！");
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
					response);
			return;
		}

	}

	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 校验验证码 1. 从session中获取正确的验证码 2. 从表单中获取用户填写的验证码 3. 进行比较！ 4.
		 * 如果相同，向下运行，否则保存错误信息到request域，转发到login.jsp
		 */
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		
		
		
		
		String sessionCode = null;
		String paramCode =null;
		if(config.getVerifyCode().equals("1")){
			sessionCode = (String) request.getSession().getAttribute(
					"session_vcode");
			paramCode = request.getParameter("vcode");
		}
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String ip = request.getRemoteAddr();// 获取客户端的ip
		
		boolean isLogin=onlineMap.getOnlineUserMap().containsKey(ip);
		if(isLogin){
			request.setAttribute("msg", "请不要重复刷新！");
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/loginSucc.jsp").forward(request,
					response);
		}

		if ((username.equals("")) || (username == null)) {
			request.setAttribute("msg", "用户名不能为空！");
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
					response);
			return;
		}
		if ((password.equals("")) || (password == null)) {
			request.setAttribute("msg", "密码不能为空！");
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
					response);
			return;
		}

		if(config.getVerifyCode().equals("1")){
			if (!paramCode.equalsIgnoreCase(sessionCode)) {
				request.setAttribute("msg", "验证码错误！");
				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
						response);
				return;
			}
		}
		

		if(config.getDebug().equals("1")){
			logger.info("请求认证    用户：" + username + " 密码:" + password + " IP地址:"
					+ ip);
		}


		/**
		 * 开始验证
		 */
		Boolean info = false;
		ServletContext sc=request.getServletContext();
		if(config.getAuth_interface().equals("1")){
			
			int state=checkLocalAccount(sc,username,password);
			if(state==0){
				request.setAttribute("msg", "用户名密码错误,或账户已过期！！");
				RequestDispatcher qr = request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp");
				qr.forward(request, response);
				return;
			}
			
			if(!checkTimeOut(sc)){
				request.setAttribute("msg", "账户已过期，请及时联系管理员充值！！");
				RequestDispatcher qr = request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp");
				qr.forward(request, response);
				return;
			}
			
			info = InterfaceControl.Method("PORTAL_LOGIN", config.getBas_user(),
					config.getBas_pwd(), ip);
			
			
			//判断用户类型建立计费信息
			/**
			 * 判断用户类型建立计费信息
			 */
			if (info == true) {
				recordId=doLinkRecord(sc,username,ip);
			}
			
			
		}else{
			info = InterfaceControl.Method("PORTAL_LOGIN", username,
					password, ip);
		}
		
		
		
		if (info == true) {
			Cookie cookie = new Cookie("uname", username);
			cookie.setMaxAge(60 * 60 * 24);
			response.addCookie(cookie);
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			session.setAttribute("password", password);
			session.setAttribute("ip", ip);
			request.setAttribute("msg", "认证成功！");
			
			//将用户和IP加入在线列表
			String[] loginInfo=new String[4];
			loginInfo[0]=username;
			loginInfo[1]=String.valueOf(userId);
			loginInfo[2]=String.valueOf(recordId);
			
			Date now=new Date();
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); 
    		loginInfo[3]=format.format(now);
			
			onlineMap.getOnlineUserMap().put(ip,loginInfo);
			
//			ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
			ApplicationContext ac = SpringContextHelper.getApplicationContext();
			
			//新建登陆日志
			LogRecord logRecord=new LogRecord();
			Date nowDate=new Date();
			
			if(config.getAuth_interface().equals("1")){
				logRecord.setInfo("本地用户，IP:"+ip+",用户："+username+",登录成功!");
			}else {
				logRecord.setInfo("外部用户，IP:"+ip+",用户："+username+",登录成功!");
			}
			
			logRecord.setRec_date(nowDate);
			LogRecordService logRecordService=(LogRecordService) ac.getBean("logRecordServiceImpl");
			logRecordService.save(logRecord);
			
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/loginSucc.jsp").forward(request,
					response);
		} else {

			request.setAttribute("msg", "认证失败！！");
			RequestDispatcher qr = request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp");
			qr.forward(request, response);
		}
	}
	
	private int checkLocalAccount(ServletContext sc,String username,String password){
		// 获取容器与相关的Service对象
//				ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		ApplicationContext ac = SpringContextHelper.getApplicationContext();
						
				AccountService accountService=(AccountService) ac.getBean("accountServiceImpl");
				Account account=accountService.login(username, password);
				if(account!=null){
					userId=account.getId();
					userState=account.getState();
					userDate=account.getDate();
					userTime=account.getTime();
					return 1;
				}
				return 0;

	}
	
	/**
	 * 用户是否过期判断
	 * @param sc
	 * @param username
	 * @return
	 */
	private boolean checkTimeOut(ServletContext sc) {
//		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		ApplicationContext ac = SpringContextHelper.getApplicationContext();
		AccountService accountService=(AccountService) ac.getBean("accountServiceImpl");
		Account account=accountService.getById(userId);
		//过期用户
		if(userState.equals(String.valueOf(0))){
			return false;
		}
		//免费用户
		if(userState.equals(String.valueOf(1))){
			return true;
		}
		// 买断用户
		if (userState.equals(String.valueOf(3))) {
			Date now = new Date();
			if (userDate.getTime() > now.getTime()) {
				return true;
			} else {
				account.setState(String.valueOf(2));
				accountService.update(account);
				userState=String.valueOf(2);
			}
		}
		//计时用户
		if(userState.equals(String.valueOf(2))){
			if(userTime>0){
				return true;
			}else {
				account.setState(String.valueOf(0));
				accountService.update(account);
				return false;
			}
		}
		return false;
	}

	/**
	 * 上线日志
	 * @param sc
	 * @param username
	 * @param ip
	 */
	private Long doLinkRecord(ServletContext sc,String username,String ip){
//		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		ApplicationContext ac = SpringContextHelper.getApplicationContext();
		LinkRecordService linkRecordService=(LinkRecordService) ac.getBean("linkRecordServiceImpl");
		
		LinkRecord linkRecord=new LinkRecord(ip, username, userState, new Date(), userId);
		linkRecordService.save(linkRecord);
		return linkRecord.getId();
	}

}
